package com.dodoke.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import com.dodoke.common.config.DodokeConfig;
import com.dodoke.common.config.ServerConfig;
import com.dodoke.common.constant.Constants;
import com.dodoke.common.exception.file.ImageUploadFailedException;
import com.dodoke.common.utils.bean.BeanUtils;
import com.dodoke.common.utils.file.FileUploadUtils;
import com.dodoke.common.utils.file.FileUtils;
import com.dodoke.domain.WxImage;
import com.dodoke.domain.vo.WxImageVo;
import com.dodoke.framework.manager.AsyncManager;
import com.dodoke.mapper.WxImageMapper;
import com.dodoke.service.IWxImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【图片】Service业务层处理
 *
 * @author dodoke
 * @date 2020-08-25
 */
@Service
public class WxImageServiceImpl implements IWxImageService {
    @Autowired
    private WxImageMapper wxImageMapper;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询【图片】
     *
     * @param goodsId 【商品】ID
     * @return 【图片结果集】
     */
    @Override
    public List<WxImage> selectWxImageByGoodsId(Long goodsId) {
        return wxImageMapper.selectWxImageByGoodsId(goodsId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param wxImage 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<WxImage> selectWxImageList(WxImage wxImage) {
        return wxImageMapper.selectWxImageList(wxImage);
    }

    /**
     * 新增【图片】
     *
     * @param goodsId      商品Id
     * @param imageUrlList 【图片列表】
     * @return 影响行数
     */
    @Override
    public int insertWxImage(Long goodsId, MultipartFile[] imageUrlList) {
        List<String> list = new ArrayList<>(10);
        int affectNum = 0;
        // 如果上传的图片不为空
        if (imageUrlList != null && imageUrlList.length > 0) {
            for (MultipartFile multipartFile : imageUrlList) {
                try {
                    // 遍历上传图片的数组，然后上传其中的每一张图片
                    String filename = FileUploadUtils.upload(multipartFile);
                    // 将图片文件名加入进集合
                    String url = serverConfig.wholeProjectUrl();
                    filename = serverConfig.getContextPath().equals("/")?
                            url.substring(0,url.length()-1)+filename:url+filename;
                    list.add(filename);
                } catch (IOException e) {
                    throw new ImageUploadFailedException(500, "图片上传失败");
                }
            }
            // 获取到当前上传的商品id，获取到商品对应的图片集合，向数据库插入
            affectNum = wxImageMapper.insertWxImage(goodsId, list);

        }
        return affectNum;
    }

    /**
     * 删除【图片】
     *
     * @return 影响行数
     */
    @Override
    public int deleteWxImageById(WxImage wxImage) {
        // 将数据库对应的记录删除
        Long id = wxImage.getId();
        int affectNum = wxImageMapper.deleteWxImageById(id);
        AsyncManager me = AsyncManager.me();
        me.execute(new TimerTask() {
            @Override
            public void run() {
                // 异步将本地磁盘上的图片资源也删除
                String imageUrl = wxImage.getImageUrl();
                StringBuilder stringBuilder = new StringBuilder();
                // 项目的路径长度
                String servletPath = serverConfig.getContextPath().equals("/")?"":serverConfig.getContextPath();
                int index = stringBuilder.append(Constants.HTTP)
                        .append(ServerConfig.getIP())
                        .append(":")
                        .append(serverConfig.getPort())
                        .append(servletPath).toString().length();
                String filename = DodokeConfig.getProfile() + imageUrl.substring(index + Constants.RESOURCE_PREFIX.length());
                FileUtils.deleteFile(filename);
            }
        });
        return affectNum;
    }


}
